package com.soonfor.evaluate.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jesse.nativelogger.NLogger;

import com.estronger.shopmanage.R;
import com.google.gson.Gson;
import com.soonfor.evaluate.adapter.PhotoAdapter;
import com.soonfor.evaluate.bean.EvaluateListBean;
import com.soonfor.evaluate.bean.ReplyDataBean;
import com.soonfor.evaluate.tools.FullyGridLayoutManager;
import com.soonfor.evaluate.tools.NoDoubleClickUtils;
import com.soonfor.evaluate.base.EvalBaseActivity;
import com.soonfor.evaluate.bean.EvaluateListDetailBean;
import com.soonfor.evaluate.bean.RequestTemplateDto;
import com.soonfor.evaluate.bean.ReturnVisitBean;
import com.soonfor.evaluate.presenter.Evaluate_CustomerToMeDetailPresenter;
import com.soonfor.evaluate.view.EvaluateDetailView;
import com.soonfor.evaluate.view.EvaluateReturnVisitView;

/**
 * 作者：DC-DingYG on 2018-10-17 19:47
 * 邮箱：dingyg012655@126.com
 */
public class Evaluate_CustomersToMeDetailActivity extends EvalBaseActivity<Evaluate_CustomerToMeDetailPresenter> {

    private Activity mActivity;
    private final int REQUEST_CODE_CTM = 1011;
    private final int REQUEST_CODE_Reply = 1012;

    @BindView(R.id.tvfLeftTilte)
    TextView tvfLeftTilte;
    @BindView(R.id.tvfRightTilte)
    TextView tvfRightTilte;
    @BindView(R.id.imgfLeftVernier)
    ImageView imgfLeftVernier;
    @BindView(R.id.imgfRightVernier)
    ImageView imgfRightVernier;

    @BindView(R.id.edView)
    EvaluateDetailView edView;

    @BindView(R.id.llfRtnVisit)
    LinearLayout llfRtnVisit;
    @BindView(R.id.tvfTotalPoints)
    TextView tvfTotalPoints;
    @BindView(R.id.ervView)
    EvaluateReturnVisitView ervView;

    @BindView(R.id.tvfToEvaluateClient)
    TextView tvfToEvaluateClient;

    @BindView(R.id.llfReplay)
    LinearLayout llfReplay;
    @BindView(R.id.tvfReplyTime)
    TextView tvfReplyTime;
    @BindView(R.id.tvfReplyContent)
    TextView tvfReplyContent;
    @BindView(R.id.rvfReplyPics)
    RecyclerView rvfReplyPics;

    @BindView(R.id.rlfReply)
    RelativeLayout rlfReplay;
    private GridLayoutManager manager;
    private PhotoAdapter adapter;
    private int ItemPositon;
    private EvaluateListBean listBean;
    public List<ReturnVisitBean> rvbList;//人工回访问题集合
    private Map<Integer, ReplyDataBean> replyMap;//回复数据
    private int evalClientStatus = 0;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_evaluate_clients_to_me_detail;
    }

    @Override
    protected void initPresenter() {
        if (rvbList == null) rvbList = new ArrayList<>();
        else if (rvbList.size() > 0) rvbList.clear();
        if(replyMap==null) replyMap = new HashMap<>();
        else if(replyMap.size()>0) replyMap.clear();
        mActivity = Evaluate_CustomersToMeDetailActivity.this;
        presenter = new Evaluate_CustomerToMeDetailPresenter(this);
    }

    @Override
    protected void initViews() {
        ((TextView) toolbar.findViewById(R.id.tvfTitile)).setText("评价详情");
        ItemPositon = getIntent().getIntExtra("List_Position", -1);
        listBean = (EvaluateListBean) getIntent().getSerializableExtra("EvaluateListBean");
        if (mSwipeRefresh != null) {
            mSwipeRefresh.setEnableLoadmore(false);
            mSwipeRefresh.autoRefresh();
        }
    }

    @Override
    public void RefreshData(boolean isRefresh) {
        super.RefreshData(isRefresh);
        if (listBean != null && !listBean.getFappraiseoriid().equals("")) {
            presenter.getEvalDetailData(false, listBean.getFappraiseoritype(), listBean.getFappraiseoriid());
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    presenter.getRtnInfo(listBean.getFrtnvisitplantaskid());
                }
            }, 500);
        }
    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }

    //处理详情信息
    public void setGetDetail(boolean isSuccess, final EvaluateListDetailBean detailBean) {
        if (detailBean != null) {
            //评价客户状态
            ArrayList<String> replayPics = new ArrayList<>();
            evalClientStatus = detailBean.getFappraisecststate();
            replyMap.put(0, detailBean.getReplyDataBean());
            if(imgfLeftVernier.getVisibility() == View.VISIBLE) {
                changeTab(0);
            }
            edView.initEvaluateDetailView(mActivity, detailBean);
        }else {
            showNoDataHint("未取到详情数据");
        }
        finishRefresh();
    }

    //处理人工回访界面
    public void setGetReturnVisit(boolean isSuccess, List<ReturnVisitBean> rvbeans, ReplyDataBean replyDataBean) {
        if (isSuccess) {
            if(rvbeans.size() > 0) {
                rvbList = rvbeans;
                ervView.initEvaluateReturnVisitView(mActivity, false, rvbList, new EvaluateReturnVisitView.TotalPoints() {
                    @Override
                    public void setTotalPoints(int scores, List<ReturnVisitBean> result) {
                        tvfTotalPoints.setText(scores + "分");
                    }
                });
                replyMap.put(1, replyDataBean);
            }
            if (imgfRightVernier.getVisibility() == View.VISIBLE) {
                changeTab(1);
            }
        }
    }
    /**
     * 设置回复view
     */
    private void setReplayView(final ReplyDataBean replyDataBean){
        if(replyDataBean!=null && !replyDataBean.getFreplydate().equals("")) {
            rlfReplay.setVisibility(View.GONE);
            llfReplay.setVisibility(View.VISIBLE);
            showDataToView(null);
            closeLoadingDialog();
            final ArrayList<String> replayPics = replyDataBean.getImgpaths();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                tvfReplyTime.setText(replyDataBean.getFreplydate());
                                tvfReplyContent.setText(replyDataBean.getFreply());
                                if (replayPics.size() > 0) {
                                    manager = new FullyGridLayoutManager(mActivity, 3);
                                    adapter = new PhotoAdapter(mActivity, replayPics, PhotoAdapter.TYPE_URL, false);
                                    adapter.setListener(new PhotoAdapter.onItemClick() {
                                        @Override
                                        public void itemClick(View view, ArrayList<String> beans, int adapterPosition) {
                                            Bundle bundle1 = new Bundle();
                                            bundle1.putStringArrayList("piclists", replayPics);
                                            bundle1.putInt("position", adapterPosition);
                                            Intent intent = new Intent(mActivity, ShowPicActivity.class);
                                            intent.putExtras(bundle1);
                                            mActivity.startActivity(intent);
                                        }

                                        @Override
                                        public void deleteClick(View view, ArrayList<String> beans, int adapterPosition) {
                                        }
                                    });
                                    rvfReplyPics.setVisibility(View.VISIBLE);
                                    rvfReplyPics.setLayoutManager(manager);
                                    rvfReplyPics.setAdapter(adapter);
                                }else {
                                    rvfReplyPics.setVisibility(View.GONE);
                                }
                            }catch (Exception e){}
                        }
                    });
                }
            }).start();
        }else {
            rlfReplay.setVisibility(View.VISIBLE);
            llfReplay.setVisibility(View.GONE);
            showDataToView(null);
            closeLoadingDialog();
        }
    }
    @OnClick({R.id.rlfYEvaluateToMe, R.id.rlfNEvaluateToMe, R.id.tvfToEvaluateClient, R.id.rlfReply})
    void thisOnClick(View v) {
        switch (v.getId()) {
            case R.id.rlfYEvaluateToMe:
                changeTab(0);
                break;
            case R.id.rlfNEvaluateToMe:
                changeTab(1);
                break;
            case R.id.tvfToEvaluateClient:
                if (!NoDoubleClickUtils.isDoubleClick()) {
                    EvaluateCustomersActivity.start(mActivity, "Evaluate_CustomersToMeDetailActivity", convertToEvalCustSaveBean(listBean),
                            REQUEST_CODE_CTM);
                }
                break;
            case R.id.rlfReply:
                if (!NoDoubleClickUtils.isDoubleClick(R.id.rlfReply)) {
                    Intent intent = new Intent(mActivity, ReplyActivity.class);
                    int fifrtnvisittask = 0;//是否回访任务回复
                    if (imgfRightVernier.getVisibility() == View.VISIBLE) {
                        fifrtnvisittask = 1;
                    }else {
                    }
                    String[] arr = new String[]{listBean.getFappraiseoriid(), listBean.getFappraiseoritype()+"",
                            fifrtnvisittask+"", tvfReplyContent.getText().toString()};
                    intent.putExtra("EVALIDPRAMS", arr);
                    mActivity.startActivityForResult(intent, REQUEST_CODE_Reply);
                }
                break;
        }
    }

    private void changeTab(int index) {
        llfdata.setVisibility(View.GONE);
        llfReplay.setVisibility(View.GONE);
        tvfReplyTime.setText("");
        tvfReplyContent.setText("");
        rlfReplay.setVisibility(View.GONE);
        showNoDataHint("正在加载数据...");
        try {
            switch (index) {
                case 0:
                    tvfLeftTilte.setTextColor(Color.parseColor("#ed423a"));
                    tvfRightTilte.setTextColor(Color.parseColor("#333333"));
                    imgfLeftVernier.setVisibility(View.VISIBLE);
                    imgfRightVernier.setVisibility(View.INVISIBLE);
                    edView.setVisibility(View.VISIBLE);
                    llfRtnVisit.setVisibility(View.GONE);
                    if (evalClientStatus==0) {
                        tvfToEvaluateClient.setVisibility(View.VISIBLE);
                    } else {
                        tvfToEvaluateClient.setVisibility(View.GONE);
                    }
                    if (replyMap.containsKey(0)) {
                        setReplayView(replyMap.get(0));
                    }
                    break;
                case 1:
                    tvfRightTilte.setTextColor(Color.parseColor("#ed423a"));
                    tvfLeftTilte.setTextColor(Color.parseColor("#333333"));
                    imgfRightVernier.setVisibility(View.VISIBLE);
                    imgfLeftVernier.setVisibility(View.INVISIBLE);
                    tvfToEvaluateClient.setVisibility(View.GONE);
                    if (listBean.getFrtnvisitstate() == 1) {
                        if (rvbList != null && rvbList.size() > 0) {
                            llfRtnVisit.setVisibility(View.VISIBLE);
                            edView.setVisibility(View.GONE);
                        } else {
                            llfRtnVisit.setVisibility(View.GONE);
                            edView.setVisibility(View.GONE);
                            showNoDataHint("未获取到回访数据");
                        }
                        if (replyMap.containsKey(1)) {
                            setReplayView(replyMap.get(1));
                        }
                    } else if(listBean.getFrtnvisitstate()==3){
                        showNoDataHint("不需回访，暂无回访详情");
                        closeLoadingDialog();
                    }else {
                        showNoDataHint("尚未回访，暂无回访详情");
                        closeLoadingDialog();
                    }
                    break;
            }
        } catch (Exception e) {
            NLogger.e("切换页签：" + e.getMessage());
            closeLoadingDialog();
        }
    }

    /**
     * 转为上传所需的EvalCustSaveBean对象
     */
    public RequestTemplateDto convertToEvalCustSaveBean(EvaluateListBean mstDto) {
        Gson gson = new Gson();
        if (mstDto != null) {
            RequestTemplateDto result = gson.fromJson(gson.toJson(mstDto), RequestTemplateDto.class);
            result.setGetdatatype("1");
            return result;
        } else return null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && data != null) {
            switch (requestCode) {
                case REQUEST_CODE_CTM:
                    tvfToEvaluateClient.setVisibility(View.GONE);
                   // ectBean.setFappcstifuse(1);
                    break;
                    case REQUEST_CODE_Reply:
                        if (imgfLeftVernier.getVisibility() == View.VISIBLE) {
                            presenter.getEvalDetailData(false, listBean.getFappraiseoritype(), listBean.getFappraiseoriid());
                        } else if (imgfRightVernier.getVisibility() == View.VISIBLE) {
                            presenter.getRtnInfo(listBean.getFrtnvisitplantaskid());
                        }
                        break;
            }
        }
    }
}
